<template>
  <view class="page">
    <view class="page-main">
      <u-form class="form" :model="model" :rules="rules" ref="uForm" label-position="left">
        <view class="form-section">
          <u-form-item label="手机号" prop="receivers" label-width="146" required>
            <u-input type="input" placeholder="请输入手机号码" v-model="model.receivers" height="80" maxlength="1024"
              :disabled="disabled"></u-input>
          </u-form-item>
          <view v-if="!disabled && hasPermission('msgReceiveBatch_selectGroupMobile')" class="btn"
            @click="chooseReceiver">
            <u-icon name="checkmark"></u-icon>
            <text>通讯录</text>
          </view>
          <view v-if="!disabled && hasPermission('msgReceiveBatch_selectSysMobile')" class="btn"
            @click="chooseSysReceiver">
            <u-icon name="checkmark"></u-icon>
            <text>系统用户</text>
          </view>
          <JsChooseGroup ref="receiverRef" v-if="hasPermission('msgReceiveBatch_selectGroupMobile')"
            @submit="doSelected" :mode="popup.mode"></JsChooseGroup>
          <JsChooseUser ref="chooseUser" v-if="hasPermission('msgReceiveBatch_selectSysMobile')" @submit="doSysSelected"
            :mode="popupSys.mode" :defaultVaule="model.userList" :multiple="popupSys.multiple"
            action="/api/blade-system/user/user-list-by-dept-type"></JsChooseUser>
          <view v-if="!disabled" class="form-count">当前录入号码：<text class="primary">{{ phoneNum }}</text></view>
          <view v-if="!disabled" class="form-tips">注意：多个号码请用逗号 或
            换行分隔，重复、无效的号码提交后会被过滤!</view>
          <view class="form-buttons">
            <view class="btn danger" @click="removeRepeat">去重</view>
            <view class="btn danger" @click="removeInvalid">清除无效</view>
            <view class="btn danger" @click="removeAll">清除所有</view>
          </view>
        </view>
        <view class="form-section">
          <u-form-item label="短信内容" prop="msgContent" label-width="146" label-position="top" required>
            <u-input type="textarea" placeholder="请输入短信内容" v-model="model.msgContent" height="128" maxlength="70"
              @input="sumFont" :disabled="disabled" />
          </u-form-item>
          <view v-if="!disabled" class="right-buttons">
            <view class="btn" @click="chooseTemplate">
              <u-icon name="checkmark"></u-icon>
              <text>选择</text>
            </view>
          </view>
          <u-picker v-model="templateShow" mode="selector" :range="templateRange" @confirm="handleTemplateConfirm"
            @cancel="templateShow = false" :range-key="rangKey"></u-picker>
          <view v-if="!disabled" class="form-count">
            当前剩余字数：<text class="primary">{{ remainNum }}/{{totalNum}}</text>
          </view>
          <view v-if="!disabled" class="form-tips">
            注意：短信超过{{totalNum}}个字符将会拆分成多条计费(包含签名)，最大支持350个字符!</view>
        </view>
        <u-form-item label="发送方式" prop="sendType" label-width="146" required>
          <js-radio v-model="model.sendType" dict-type="sendType" itemLabel="dictValue" itemValue="dictKey"
            :disabled="disabled"></js-radio>
        </u-form-item>
        <u-form-item v-if="model.sendType=='2'" label="发送时间" prop="sendDate" label-width="146" required count>
          <view v-if="disabled">
            {{model.sendDate}}
          </view>
          <view v-else @click="sendDateShow = true" style="width: 100%;">
            <view>{{model.sendDate==''?'请选择时间':model.sendDate}}</view>
            <u-picker v-model="sendDateShow" mode="time" :params="params" @confirm="handleDateConfirm"
              disabled="disabled">
            </u-picker>
          </view>
        </u-form-item>
      </u-form>
    </view>
    <view v-if="!disabled" class="page-footer">
      <view class="button" @click="submit">保存</view>
      <view class="button" @click="cancel">取消</view>
    </view>
    <view v-else class="page-footer">
      <view v-if="hasPermission('msgReceiveBatch_edit')" class="button" @click="disabled=false">编辑</view>
      <view v-if="hasPermission('msgReceiveBatch_delete')" class="button" @click="handleDelete">删除</view>
    </view>
    <!-- <view class="footer">
      <view v-if="!disabled" style="display: flex;flex-direction: row; margin-top: 20rpx;">
        <u-button class="btn" style="width: 50%;margin-right: 10rpx;" type="primary" @click="submit">保存</u-button>
        <u-button class="btn" style="width: 50%;" @click="cancel">取消</u-button>
      </view>
      <view v-else>
        <u-button class="btn" style="width: 50%;margin-right: 10rpx;" type="primary"
          v-if="hasPermission('msgReceiveBatch_edit') && model.status === 6 && model.createUser==this.vuex_userId "
          @click="disabled=false">编辑</u-button>
        <u-button class="btn" type="error"
          v-if="hasPermission('msgReceiveBatch_delete') && model.status === 6 && model.createUser==this.vuex_userId"
          @click="handleDelete">删除</u-button>
      </view>
    </view> -->
  </view>
</template>
<script>
  import JsChooseGroup from '@/components/js-choose-group/js-choose-group.vue'
  import JsChooseUser from '@/components/js-choose-user-popup/js-choose-user-popup.vue'
  import {
    validatenull
  } from '@/common/validate.js'
  export default {
    components: {
      JsChooseGroup,
      JsChooseUser
    },
    data() {
      return {
        model: {
          id: '',
          channelType: '1',
          receivers: '',
          msgContent: '',
          sendType: '1',
          sendDate: '',
          batchId: '',
          templateId: '',
          userList: []
        },
        params: {
          year: true,
          month: true,
          day: true,
          hour: true,
          minute: true,
          second: true
        },
        popup: {
          show: false,
          mode: "bottom"
        },
        popupSys: {
          show: false,
          mode: "bottom",
          multiple: false,
        },
        templateRange: [],
        templateList: [],
        templateShow: false,
        sendDateShow: false,
        rangKey: 'name',
        phoneNum: 0,
        fontNum: 0,
        totalNum: 70,
        remainNum: 0,
        disabled: true,
        rules: {
          receivers: [{
            required: true,
            message: '请输入手机号码',
            trigger: ['change', 'blur'],
          }],
          msgContent: [{
            required: true,
            message: '请输入短信内容',
            trigger: ['change', 'blur'],
          }],
          sendDate: [{
            required: true,
            message: '请选择发送时间',
            trigger: ['change', 'blur'],
          }],
          sendType: [{
            required: true,
            message: '请选择发送类型',
            trigger: ['change', 'blur'],
          }]
        },
      };
    },
    onLoad(params) {
      if (params.id) {
        this.$u.api.message.msgReceiveBatch.detail({
          id: params.id
        }).then(res => {
          Object.assign(this.model, res.data);
          this.model.sendType = res.data.sendType.toString();
          if (this.hasPermission('msgReceiveBatch_edit') && this.model.status === 6 && this.model.createUser == this
            .vuex_userId) {
            this.disabled = false;
            this.calcMobile();
            this.calcFontNum();
          }
        });
      } else {
        this.disabled = false;
        this.model.batchId = this.getBatchId();
      }
    },
    onReady() {
      this.$refs.uForm.setRules(this.rules);
      this.$u.api.message.msgTemplate.templateDict().then(res => {
        this.templateRange = res.data.map(item => (item.name));
        this.templateList = res.data;
      });
    },
    methods: {
      submit() {
        this.$refs.uForm.validate(valid => {
          if (valid) {
            uni.showLoading({
              title: '提交中....'
            })
            this.$u.api.message.msgReceiveBatch.save(this.model).then(res => {
              uni.hideLoading();
              uni.showModal({
                title: '提示',
                content: res.msg,
                showCancel: false,
                success: function() {
                  if (res.code == 200) {
                    uni.navigateTo({
                      url: 'index'
                    });
                  }
                }
              });
            });
          } else {
            this.$u.toast('您填写的信息有误，请根据提示修正。');
          }
        });
      },
      cancel() {
        uni.navigateTo({
          url: 'index'
        });
      },
      handleDateConfirm(e) {
        this.model.sendDate = e.year + '-' + e.month + '-' + e.day + ' ' + e.hour + ":" + e.minute + ":" + e.second;
        this.sendDateShow = false;
      },
      handleTemplateConfirm(e) {
        let row = this.templateList[e[0]];
        this.model.msgContent = row.templateContent;
        this.templateShow = false;
      },
      getBatchId() {
        let date = new Date();
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let day = date.getDate();
        month = (month > 9) ? month : ("0" + month);
        day = (day < 10) ? ("0" + day) : day;
        var batchId = year + "" + month + "" + day + '' + date.getTime();
        return batchId;
      },
      chooseTemplate() {
        this.popup.show = false;
        this.templateShow = true;
      },
      chooseReceiver() {
        this.$refs.receiverRef.open();
        this.templateShow = false;
      },
      doSelected() {
        let userData = this.$refs.receiverRef.getData();
        let receiver = [];
        userData.selectedData.forEach((item) => {
          receiver.push(item.phone);
          if (userData.byCheck1) {
            receiver.push(item.phone1);
          } else if (userData.byCheck2) {
            receiver.push(item.phone2);
          } else if (userData.byCheck3) {
            receiver.push(item.phone3);
          } else if (userData.byCheck4) {
            receiver.push(item.phone4);
          }
        })
        this.model.receivers = receiver.join(",");
        // this.$refs.receiverRef.clearAll();
        this.removeRepeat();
        this.removeInvalid();
        this.$refs.receiverRef.close();
      },
      isCMCC(mobile) {
        if (mobile) {
          return mobile.match(
            /^(\+86)?(134[0-8]\d{7}|13[56789]\d{8}|14[78]\d{8}|15[012789]\d{8}|165\d{8}|170[356]\d{7}|17[28]\d{8}|18[23478]\d{8}|19[578]\d{8})$/g
          );
        } else {
          return false;
        }
      },
      isUnicom(mobile) {
        if (mobile) {
          return mobile.match(
            /^(\+86)?(13[012]\d{8}|1400\d{7}|14[56]\d{8}|15[56]\d{8}|16[67]\d{8}|170[4789]\d{7}|17[156]\d{8}|18[56]\d{8}|196\d{8})$/g
          );
        } else {
          return false;
        }
      },
      isTelecom(mobile) {
        if (mobile) {
          return mobile.match(
            /^(\+86)?(133\d{8}|1349\d{7}|14[19]\d{8}|153\d{8}|162\d{8}|170[012]\d{7}|17[347]\d{8}|18[019]\d{8}|19[01239]\d{8})$/g
          );
        } else {
          return false;
        }
      },
      removeRepeat() {
        var txt = this.model.receivers;
        if (!txt) return;
        var val = txt.replace(/\n/g, ",");
        val = val.replace(/\s/g, "");
        val = val.replace(/,{2,}/g, ",");
        var mobiles = val.split(",", this.maxMobileNum);
        var mobile;
        for (var i = 0; i < mobiles.length; i++) {
          mobile = mobiles[i]
          if (mobile == "") {
            mobiles.splice(i--, 1);
          } else if (!(this.isCMCC(mobile) || this.isUnicom(mobile) || this.isTelecom(mobile))) {
            mobiles.splice(i--, 1);
          } else {
            mobile = mobile.replace(/^\+86/g, "");
            mobiles[i] = mobile;
            for (var j = 0; j < i; j++) {
              if (mobile == mobiles[j]) {
                mobiles.splice(i--, 1);
                break;
              }
            }
          }
        }
        this.model.receivers = mobiles.join(",");
        this.calcMobile();
      },
      removeInvalid() {
        var txt = this.model.receivers;
        if (!txt) return;
        var val = txt.replace(/\n/g, ",");
        val = val.replace(/\s/g, "");
        val = val.replace(/,{2,}/g, ",");
        var mobiles = val.split(",", this.maxMobileNum);
        var mobile;
        for (var i = 0; i < mobiles.length; i++) {
          mobile = mobiles[i]
          if (mobile == "") {
            mobiles.splice(i--, 1);
          } else if (!(this.isCMCC(mobile) || this.isUnicom(mobile) || this.isTelecom(mobile))) {
            mobiles.splice(i--, 1);
          } else {
            mobiles[i] = mobile.replace(/^\+86/g, "");
          }
        }
        this.model.receivers = mobiles.join(",");
        this.calcMobile();
      },
      removeCMCC() {
        var txt = this.model.receivers;
        if (!txt) return;
        var val = txt.replace(/\n/g, ",");
        val = val.replace(/\s/g, "");
        val = val.replace(/,{2,}/g, ",");
        var mobiles = val.split(",", this.maxMobileNum);
        var mobile;
        for (var i = 0; i < mobiles.length; i++) {
          mobile = mobiles[i]
          if (mobile == "") {
            mobiles.splice(i--, 1);
          } else if (!(this.isUnicom(mobile) || this.isTelecom(mobile))) {
            mobiles.splice(i--, 1);
          } else {
            mobiles[i] = mobile.replace(/^\+86/g, "");
          }
        }
        this.model.receivers = mobiles.join(",");
        this.calcMobile();
      },
      removeUnicom() {
        var txt = this.model.receivers;
        if (!txt) return;
        var val = txt.replace(/\n/g, ",");
        val = val.replace(/\s/g, "");
        val = val.replace(/,{2,}/g, ",");
        var mobiles = val.split(",", this.maxMobileNum);
        var mobile;
        for (var i = 0; i < mobiles.length; i++) {
          mobile = mobiles[i]
          if (mobile == "") {
            mobiles.splice(i--, 1);
          } else if (!(this.isCMCC(mobile) || this.isTelecom(mobile))) {
            mobiles.splice(i--, 1);
          } else {
            mobiles[i] = mobile.replace(/^\+86/g, "");
          }
        }
        this.model.receivers = mobiles.join(",");
        this.calcMobile();
      },
      removeTelecom() {
        var txt = this.model.receivers;
        if (!txt) return;
        var val = txt.replace(/\n/g, ",");
        val = val.replace(/\s/g, "");
        val = val.replace(/,{2,}/g, ",");
        var mobiles = val.split(",", this.maxMobileNum);
        var mobile;
        for (var i = 0; i < mobiles.length; i++) {
          mobile = mobiles[i]
          if (mobile == "") {
            mobiles.splice(i--, 1);
          } else if (!(this.isCMCC(mobile) || this.isUnicom(mobile))) {
            mobiles.splice(i--, 1);
          } else {
            mobiles[i] = mobile.replace(/^\+86/g, "");
          }
        }
        this.model.receivers = mobiles.join(",");
        this.calcMobile();
      },
      removeAll() {
        this.model.receivers = "";
        this.calcMobile();
        this.$refs.receiverRef.clearAll();
      },
      calcMobile() {
        var txt = this.model.receivers;
        if (!txt) {
          this.phoneNum = 0;
          return;
        }
        var val = txt.replace(/\n/g, ",");
        val = val.replace(/\s/g, "");
        val = val.replace(/,{2,}/g, ",");
        var mobiles = val.split(",");
        var cnt = mobiles.length;
        if (cnt > 0 && mobiles[0] == "") {
          cnt--;
        }
        if (cnt > 1 && mobiles[cnt - 1] == "") {
          cnt--;
        }
        this.phoneNum = cnt;
      },
      sumFont(e) {
        if (e.length > this.totalNum) {
          this.model.msgContent = e.substring(0, this.totalNum);
          this.fontNum = this.model.msgContent.length;
          this.remainNum = this.totalNum - this.fontNum;
        } else {
          this.fontNum = e.length;
          this.remainNum = this.totalNum - this.fontNum;
        }
      },
      calcFontNum() {
        this.fontNum = this.model.msgContent.length;
        this.remainNum = this.totalNum - this.fontNum;
      },
      handleDelete() {
        let self = this;
        uni.showModal({
          title: '提示',
          content: '确认要删除该数据吗,删除后将取消发送？',
          showCancel: true,
          success: function(res2) {
            if (res2.confirm) {
              self.$u.api.message.msgReceiveBatch.delete({
                ids: self.model.id
              }).then(res => {
                self.$u.toast('删除成功！');
                uni.navigateTo({
                  url: 'index'
                });
              });
            }
          }
        });
      },
      chooseSysReceiver() {
        this.$refs.chooseUser.open();
        this.templateShow = false;
      },
      doSysSelected() {
        let userData = this.$refs.chooseUser.getData();
        let receiver = [];
        userData.forEach((item) => {
          receiver.push(item.phone);
        })
        this.model.receivers = receiver.join(",");
        // this.$refs.receiverRef.clearAll();
        this.removeRepeat();
        this.removeInvalid();
        this.$refs.chooseUser.close();
      },
    }
  };
</script>
<style lang="scss" scoped>
  .page {
    display: flex;
    flex-direction: column;
    height: 100vh;
    background: #f7f7f7;
  }

  .page-main {
    flex: 1;
    overflow: auto;
  }

  .page-footer {
    flex-shrink: 0;
    display: flex;
    padding: 24rpx;
    background: #f7f7f7;

    .button {
      flex: 1;
      height: 96rpx;
      border-radius: 96rpx;
      line-height: 96rpx;
      text-align: center;
      font-size: 32rpx;
      font-weight: 500;
      color: #fff;
      background: #3989FC;

      &+.button {
        margin-left: 24rpx;
        color: #333;
        background: #fff;
      }
    }
  }

  .form {
    padding: 32rpx 24rpx;
  }

  .form-section {
    border-radius: 8rpx;
    padding: 16rpx 32rpx;
    margin-bottom: 24rpx;
    background: #fff;

    .u-form-item {
      border-radius: 0;
      padding: 0;
      margin-bottom: 0;
    }

    /deep/ .u-form-item__message {
      margin-top: 0;
      margin-bottom: 16rpx;
    }

    .btn {
      display: inline-flex;
      align-items: center;
      height: 56rpx;
      border-radius: 56rpx;
      padding: 0 24rpx;
      line-height: 56rpx;
      font-size: 28rpx;
      font-weight: 500;
      color: #fff;
      background: #1676FE;

      &+.btn {
        margin-left: 16rpx;
      }

      &.danger {
        border-radius: 16rpx;
        background: #D43030;
      }

      .u-icon {
        display: inline-flex;
        justify-content: center;
        align-items: center;
        width: 28rpx;
        height: 28rpx;
        border-radius: 50%;
        margin-right: 8rpx;
        font-size: 24rpx;
        color: #1676FE;
        background: #fff;
      }
    }
  }

  .u-form-item {
    border-radius: 8rpx;
    padding: 16rpx 32rpx;
    margin-bottom: 24rpx;
    background: #fff;

    /deep/ .u-form-item--left__content__label {
      font-size: 28rpx;
      font-weight: 700;
      color: #333;
    }

    &::after {
      display: none;
    }
  }

  .form-count {
    margin-top: 40rpx;
    font-size: 28rpx;
    font-weight: 500;
    color: #333;

    .primary {
      color: #D43030;
    }
  }

  .form-tips {
    margin-top: 16rpx;
    font-size: 24rpx;
    font-weight: 500;
    color: #999;
  }

  .form-buttons {
    margin-top: 16rpx;
  }

  .right-buttons {
    display: flex;
    justify-content: flex-end;
    border-bottom: 1px solid #eee;
    padding-bottom: 16rpx;
  }
</style>